// pages/listen/listen.js
import {eventBusGetter} from '../../utils/eventbus';
import {EVENT_BUS_KEY, PAGE_NAME} from '../../common/constants';
import toast from '../../common/service/toast-service';
import {getLessonDetail} from '../../data-model/model-courese';
import page from '../../common/service/page-service';
import alert from '../../common/service/alter-service';
import {
    getCommentList,
    likeComment,
    deleteComment
} from '../../data-model/model-comment';
import userservice from '../../common/service/user-service';
import { setCurrentLesson, setStudiedLesson } from '../../common/service/courses-service';
import { stopBackgroundAudio } from '../../common/service/system-service';

Page({
    /**
     * 页面的初始数据
     */
    data: {
        nextId: '',
        lastPage: false,
        lessonId: '',
        lessonDetail: {},
        audioInfo: {}, // 播放音频的数据对象
        commentList: [],
        isPullDownRefreshing: true,
        from: PAGE_NAME.FROM_DETAIL,
        fromGift: PAGE_NAME.OPEN_GIFT,
        isHighest: true,
        isMiddle: true
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.data.lessonId = options.lessonId;
        if (options.from) {
            this.setData({
                from: options.from
            });
        }
        page.hideShareMenu();
        this.getLessonDetail();
        eventBusGetter().$on(EVENT_BUS_KEY.PLAY_LESSON_UPDATE, this.subscribePlayLessonUpdate);
        eventBusGetter().$on(EVENT_BUS_KEY.ADD_COMMENT_SUCCESS, this.subscribeAddComment);

        eventBusGetter().$on(EVENT_BUS_KEY.LOGIN_STATUS_UPDATE, this.subscribeLogin);
        eventBusGetter().$on(EVENT_BUS_KEY.PLAY_LESSON_NEXT, (json) => {
            this.data.lessonId = json.lessonId;
            this.getLessonDetail();
        });
        eventBusGetter().$on(EVENT_BUS_KEY.PLAY_LESSON_PREV, (json) => {
            this.data.lessonId = json.lessonId;
            this.getLessonDetail();
        });
    },
    subscribePlayLessonUpdate (json) {
        let that = this;
        that.data.lessonId = json.audioInfo.lessonId;
        that.getLessonDetail();
    },
    subscribeAddComment (json) {
        let that = this;
        let comment = json.comment;
        let list = that.data.commentList;
        list.push(comment);
        let coList = that.getCommentList(list);
        that.setData({
            commentList: coList
        });
    },
    subscribeLogin (json) {
        let that = this;
        that.setData({
            lessonDetail: {},
            audioInfo: {},
            isHighest: false,
            isMiddle: false,
            commentList: []
        });
        that.getLessonDetail();
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        eventBusGetter().$off(EVENT_BUS_KEY.PLAY_LESSON_UPDATE, this.subscribePlayLessonUpdate);
        eventBusGetter().$off(EVENT_BUS_KEY.ADD_COMMENT_SUCCESS, this.subscribeAddComment);
        eventBusGetter().$off(EVENT_BUS_KEY.LOGIN_STATUS_UPDATE, this.subscribeLogin);
        eventBusGetter().$off(EVENT_BUS_KEY.PLAY_LESSON_NEXT);
        eventBusGetter().$off(EVENT_BUS_KEY.PLAY_LESSON_PREV);
    },

    onReachBottom: function () {
        console.log('onReachBottom');
        if (this.data.commentList.length > 0 && !this.data.lastPage) {
            this.getCommentListData(this.data.nextId);
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        var path = this.data.lessonDetail.giftShareInfo.miniProgramPath;
        return {
            title: this.data.lessonDetail.giftShareInfo.title,
            path: path,
            imageUrl: this.data.lessonDetail.giftShareInfo.img,
            success: function (res) {
                console.log(res);
            },
            fail: function (err) {
                console.log(err);
            }
        };
    },

    refresh () {
        this.data.isPullDownRefreshing = true;
        return this.getCommentListData('');
    },

    getCommentListData (nextId) {
        page.showNavigationBarLoading();
        var result = this.getListRequest(nextId);
        result.then(
            res => {
                // console.log("列表数据刷新成功", res);
                this.onLoadSuccess(nextId, res);
            },
            err => {
                // console.log("列表数据刷新失败", err);
                this.onLoadError(nextId, err);
            }
        );

        return result;
    },

    getListRequest (nextId) {
        let params = {};
        params['count'] = 10;
        params['nextId'] = nextId;
        return getCommentList(this.data.lessonId, params);
    },

    onLoadSuccess (nextId, data) {
        // console.log("onLoadSuccess : " + nextId);
        // console.log(data);
        page.hideNavigationBarLoading();
        this.data.nextId = data.nextId;
        this.data.lastPage = data.lastPage;
        if (this.data.commentList.length > 0 && this.data.isPullDownRefreshing === false) {
            let cList = this.getCommentList(data.data);
            this.data.commentList = this.data.commentList.concat(cList);
            this.setData({
                commentList: this.data.commentList
            });
        } else {
            if (data.data.length > 0) {
                this.data.isPullDownRefreshing = false;
            }
            let cList = this.getCommentList(data.data);
            this.setData({
                commentList: cList
            });
        }
    },

    onLoadError (nextId, err) {
        // console.log("onLoadError : " + nextId);
        page.hideNavigationBarLoading();
    },

    /*
    * 回复，删除显隐
    */
    getCommentList (commentList) {
        let list = commentList;
        let isLogin = false;
        let user = userservice.getUserInfo();
        if (user) {
            isLogin = true;
        }
        for (let i = 0; i < list.length; i++) {
            let item = list[i];
            if (isLogin === false) {
                item.isReply = true;
                item.isDelete = false;
            } else {
                if (item.uid === user.userId) {
                    item.isReply = false;
                    item.isDelete = true;
                } else {
                    item.isReply = true;
                    item.isDelete = false;
                }
            }
        }
        return list;
    },

    getAudioInfo (data) {
        // let audioInfo = {};
        // audioInfo['src'] = data.audioUrl;
        // audioInfo['coverImgUrl'] = data.courseSharePic;
        // audioInfo['title'] = data.courseTitle;
        // audioInfo['id'] = data.id;
        // return audioInfo;
        return Object.assign({}, data, {
            src: data.audioUrl,
            coverImgUrl: data.courseSharePic
        });
    },

    /**
     * 获取小节详情
     */
    getLessonDetail () {
        let that = this;
        toast.showLoading();
        getLessonDetail(this.data.lessonId)
            .then(res => {
                toast.hideLoading();
                if (res.giftShareInfo) {
                    page.showShareMenu();
                } else {
                    page.hideShareMenu();
                }
                let highest = false;
                let middle = false;
                if (that.data.from === that.data.fromGift) {
                    highest = false;
                    middle = false;
                } else {
                    if (res.contentType === 1 || res.giftShareInfo) {
                        middle = true;
                    }
                }
                if (res.contentType === 1) {
                    let audioInfo = that.getAudioInfo(res);
                    highest = true;
                    that.setData({
                        lessonDetail: res,
                        isShow: true,
                        audioInfo: audioInfo,
                        isHighest: highest,
                        isMiddle: middle
                    });
                } else {
                    highest = false;
                    that.setData({
                        lessonDetail: res,
                        isHighest: highest,
                        isMiddle: middle
                    });
                    setCurrentLesson(res);
                    setStudiedLesson(res);
                    stopBackgroundAudio();
                }

                if (res && 'courseTitle' in res && res.courseTitle.length > 0) {
                    page.setNavigationBarTitle({
                        title: res.courseTitle
                    });
                }
                that.refresh();
            })
            .catch(err => {
                toast.hideLoading();
                if (err.header && err.header.msg) {
                    let errMsg = decodeURI(err.header.msg);
                    toast.showLoadingToast(errMsg);
                }
            });
    },

    onPlayList: function () {
        let that = this;
        let url = '/pages/playlist/playlist?lessonsCount=' + this.data.lessonDetail.lessonCount + '&' + 'courseType=' + this.data.lessonDetail.courseType + '&' + 'courseTitle=' + that.data.lessonDetail.courseTitle + '&' + 'purchaseStatus=' + that.data.lessonDetail.purchaseStatus;
        page.navigateTo({
            url: url
        });
    },

    onTimeUpdate (e) {
        // // 旋转同时放大
        // let animation = wx.createAnimation({
        //   duration:1000,
        //     timingFunction:"ease",
        // })
        // this.animation = animation
        // animation.rotate(45).step();
        // this.setData({
        //   animationData:animation.export()
        // })
        // setTimeout(function(){
        //   animation.rotate(0).step();
        //   this.setData({
        //     animationData:animation.export()
        //   })
        // }.bind(this),1000);
    },

    /**
     * 点赞
     * @param {*} e
     */
    onFavour (e) {
        let item = e.detail;
        if (userservice.getUserInfo()) {
            if (item.hasLiked === 0) {
                toast.showLoading();
                let that = this;
                likeComment(item.commentId)
                    .then(res => {
                        toast.hideLoading();
                        that.addFavourCount(item.commentId);
                    })
                    .catch(err => {
                        toast.hideLoading();
                        if (err.header.msg) {
                            let errMsg = decodeURI(err.header.msg);
                            toast.showLoadingToast(errMsg);
                        }
                    });
            }
        } else {
            this.gotoLogin();
        }
    },

    /**
     * 回复
     * @param {*} e
     */
    onReply (e) {
        if (userservice.getUserInfo()) {
            let item = e.detail;
            let placeholder = '回复' + item.name + '：（限1000字）';
            this.openAddComment(
                this.data.lessonDetail.courseId,
                this.data.lessonDetail.lessonId,
                item.commentId,
                item.uid,
                placeholder
            );
        } else {
            this.gotoLogin();
        }
    },

    /**
     * 删除
     * @param {*} e
     */
    onDelete (e) {
        if (userservice.getUserInfo()) {
            let item = e.detail;
            let that = this;
            alert.showAlertModel({
                title: '是否删除当前心得?',
                cancelText: '取消',
                confirmText: '删除'
            })
                .then(res => {
                    if (res.confirm) {
                        that.deleteCommentRequest(item.commentId);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        } else {
            this.gotoLogin();
        }
    },

    /**
     * 分享
     * @param {*} e
     */
    onShare (e) {
    },

    gotoLogin () {
        page.navigateTo({
            url: '/pages/login/login'
        });
    },

    onWriteComment () {
        let user = userservice.getUserInfo();
        if (user) {
            this.openAddComment(
                this.data.lessonDetail.courseId,
                this.data.lessonDetail.lessonId,
                '',
                '',
                ''
            );
        } else {
            this.gotoLogin();
        }
    },

    openAddComment (courseId, lessonId, commentId, targetUid, placeholder) {
        let url =
            '/pages/addcomment/addcomment?courseId=' +
            courseId +
            '&' +
            'lessonId=' +
            lessonId +
            '&' +
            'commentId=' +
            commentId +
            '&' +
            'targetUid=' +
            targetUid +
            '&' +
            'placeholder=' +
            placeholder;
        page.navigateTo({
            url: url
        });
    },
    /**
     * 服务端删除评论
     */
    deleteCommentRequest (commentId) {
        toast.showLoading();
        let that = this;
        deleteComment(commentId)
            .then(res => {
                toast.hideLoading();
                that.refresh();
            })
            .catch(err => {
                toast.hideLoading();
                if (err.header.msg) {
                    let errMsg = decodeURI(err.header.msg);
                    toast.showLoadingToast(errMsg);
                }
            });
    },

    /**
     * 本地删除评论
     */
    deleteComment (commentId) {
        let list = this.data.commentList;
        for (let i = 0; i < list.length; i++) {
            let item = list[i];
            if (item.commentId === commentId) {
                list.splice(i, 1);
                break;
            }
        }
        this.setData({
            commentList: list
        });
    },

    /*
    *赞加1
    */
    addFavourCount (commentId) {
        let list = this.data.commentList;
        for (let i = 0; i < list.length; i++) {
            let item = list[i];
            if (item.commentId === commentId) {
                item.likeCount = item.likeCount + 1;
                item.hasLiked = 1;
                break;
            }
        }
        this.setData({
            commentList: list
        });
    },

    /**
     * 跳详情页
     */

    onListenCourse () {
        let url =
            '/pages/detail/detail?courseId=' + this.data.lessonDetail.courseId;

        if (this.data.from === PAGE_NAME.OPEN_GIFT) {
            page.reLaunch({
                url: url
            });
        } else {
            page.navigateBack({
                delta: 1
            });
        }
    }
});
